<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ApiserverController
 *
 * @author NE
 */
class Backend_ApiserverController extends RCMS_Core_BaseapiController {

	private $_websiteUrl = '';

	const AFF_FILE_NAME = 'af.id';

	const AFF_FILE_PATH = 'tmp/';

	/**
	 * Init method of API server
	 *
	 */
	public function init() {
		parent::init();
		$this->_model = new Backend_ApiserverModel();
		$this->_updater = new RCMS_Object_Updater_Updater();
		$this->_websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
	}

	/**
	 * Main action of API server. This action takes request parameters and pass them to the delegate action
	 * Reads the result of operation and sends encoded response
	 *
	 */
	public function indexAction() {
		parent::indexAction();
		$this->_sendEncodedResponse($this->_delegate());
	}

	/**
	 * Creates a valid call to needed API section
	 *
	 * @return mixed
	 */
	private function _delegate() {
		$action = '_' . $this->_section . $this->_param;
		if($action != '_clientauthorize') {
			if(!$this->_apiSecurity->checkAuthdescriptor()) {
				$this->_sendErrorResponse('bad_auth');
				die();
			}
		}
		return $this->$action();
	}

	/**
	 * Api action. Section: website, Action: getallpages
	 *
	 * @return array
	 */
	private function _websitegetallpages() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$catPages    = $this->_model->getWebsitePages();
		if(!empty($catPages)) {
			foreach($catPages as $key => $category) {
				$catPages[$key] = array_map(array($this, '_pagesCallback'), $category);
				$catPages[$key]['pages'] = $this->_model->getWebsitePages($category['categoryId']);
				if(!empty($catPages[$key]['pages'])) {
					foreach($catPages[$key]['pages'] as $subKey => $page) {
						$catPages[$key]['pages'][$subKey] = array_map(array($this, '_pagesCallback'), $page);
					}
				}
			}
		}

		return $catPages;
	}

	private function _pagesCallback($value) {
		return utf8_encode($value);
	}

	private function _websitegetredirects() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$redirects = $this->_model->getRedirects();
		if(!empty($redirects)) {
			return $redirects;
		}
		return array();
	}

	private function _websitegetrobots() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$robotsContent = RCMS_Tools_FilesystemTools::getFile('robots.txt');
		return $robotsContent;
	}

	private function _websiteupdatepages() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$pages = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('pages')));
		return $this->_updater->updatePages($pages);
	}

	private function _websiteupdatelanguage() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$languageName = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('languagename')));
		return $this->_updater->updateLanguageName($languageName);
	}


	private function _websitegetalldeeplinks() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$deeplinks = $this->_model->getDeeplinks();
		foreach ($deeplinks as $key => $deeplinkData) {
			$parsed = parse_url($deeplinkData['url']);
			if($deeplinkData['type'] != RCMS_Object_Deeplink_Deeplink::TYPE_EXTERNAL) {
				$url = str_replace(array('.html'), '', ltrim($parsed['path'], '/'));
				$pageId = $this->_model->getPageIdByDeeplinkUrl($url);
			}
			else {
				$pageId = '';
			}
			$deeplinks[$key]['rcmsPid'] = $pageId;
		}
		return $deeplinks;
	}

	private function _websiteupdatedeeplinks() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$deeplinks = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('deeplinks')));
		return $this->_updater->updateDeeplinks($deeplinks);
	}

	private function _websiteupdatenews() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$news = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('news')));
		return $this->_updater->updateNews($news);
	}

	private function _websiteupdatenewssm() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$newsSiteMap = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('newssm')));
		return $this->_updater->updateNewsSitemap($newsSiteMap);
	}

	private function _websiteupdateindexsm() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$indexSitemap = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('indexsm')));
		return $this->_updater->updateIndexSitemap($indexSitemap);
	}

	private function _websiteupdaterssfeeds() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$rssFeeds = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('rssfeeds')));
		return $this->_updater->updateRssFeeds($rssFeeds);
	}

	private function _websiteupdatevars() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$vars = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('vars')));
		return $this->_updater->updateVariables($vars);
	}

	private function _websiteupdateseovars() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$seoData = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('seo')));
		return $this->_updater->updateSeoVars($seoData);
	}

	private function _websiteupdateservices() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$servicesContent = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('servContent')));
		return $this->_updater->updateServices($servicesContent);
	}

	private function _websiteupdateverification() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$verificationData = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('verification')));
		return $this->_updater->updateVerification($verificationData);
	}

	private function _websiteupdaterobotstxt() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		return $this->_updater->updateRobotsTxt($this->_websiteUrl . 'sitemapindex.xml');
	}

	private function _affiliategetid() {
		$this->_helper->viewRenderer->setNoRender(true);
		$this->_helper->getHelper('layout')->disableLayout();
		$affFile = '../' . self::AFF_FILE_PATH . self::AFF_FILE_NAME;
		try {
			$affFileContent = RCMS_Tools_FilesystemTools::getFile($affFile);
		}
		catch (Exception $e) {
			$affFileContent = null;
		}
		return $affFileContent;
	}

	private function _clientauthorize() {
		$this->_helper->viewRenderer->setNoRender(true);
		$login = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('login'));
		$password = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('password'));
		if(!empty ($login) && !empty ($password)) {
			$userExistsId = $this->_apiSecurity->checkUserByLoginAndPass($login,$password);
			if(!$userExistsId) {
				return 'Error. System doesn\'t know this user';
			}
			$authDescriptor = $this->_apiSecurity->generateAuthHashCode($login, $password);
			$this->_apiSecurity->saveAuthDescriptor($userExistsId, $authDescriptor);
			return 'Auth='.$authDescriptor;
		}
		return 'Bad request. Some arguments are missing.';
	}
}

